<template>
  <div class="v-html-textarea">
    <span
      v-if="isCreateElement"
      class="v-editor-createElement"
    >
      <span v-if="encrypted">{{ desensitize("查看与编辑包结构信息") }}</span>
      <span v-else>{{ $t("查看与编辑包结构信息") }}</span>
      <div class="img-btn">
        <img
          v-if="selected"
          src="statics/icons/app/iconmore.png"
          class="g-pointer"
          @click="handleEditPackageInfo"
        />
      </div>
    </span>
    <span v-else-if="encrypted">{{ desensitize(text) }}</span>
    <template v-else>
      <HTMLViewer
        v-if="isAHtmlItem"
        style="overflow: auto; flex: 1 1 100px; padding-top: 3px; min-height: 23px"
        :projectId="projectId"
        :htmlText="text"
        @click.prevent
      />

      <div
        v-else
        class="v-editor-textarea"
      >
        <el-input
          v-if="selected"
          v-model="text"
          type="textarea"
          :style="{ height: editDivHeight }"
          :maxlength="maxlength"
          :disabled="row.readonly || isModelDisabled"
          :inputStyle="{ minHeight: '24px' }"
          @change="handelChange"
        />
        <div
          v-if="!selected"
          ref="showDiv"
          class="g-pd-lr-7"
        >
          <span v-if="containTermName.length">
            <span
              v-for="(item, index) in containTermName"
              :key="index"
            >
              <span
                v-if="item.isTerm"
                class="show-underline"
                @contextmenu.stop="event => showDetailTerm(event, item.name)"
              >
                {{ item.name }}
              </span>
              <span v-else>{{ item.name }}</span>
            </span>
          </span>
          <span v-else>{{ text }}</span>
        </div>
      </div>

      <div
        v-if="needHtmlEntry"
        :disabled="row.readonly || isModelDisabled"
        class="img-btn"
      >
        <img
          v-if="selected"
          src="statics/icons/app/iconmore.png"
          class="g-pointer"
          @click="handleClick"
        />
      </div>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { BusEvent, PropertyKey } from "@/constants/Enums";
import { modelService } from "@/modules/model/service";
import { ref, watch, Ref, inject, computed } from "vue";
import { propertyUtil } from "../../PropertyUtil";
import { PropertyRow } from "../../types";
import { desensitize } from "@/util/common";
import HTMLViewer from "@/modules/model/comps/common/HTMLViewer.vue";
import { GlobalNumberType } from "@/constants/StType";
import { htmlEditorWindow } from "@/modules/model/modals/htmlEditor";
import { ContainTermName, splitOriginTextWithTerms } from "@/mdesign-lib/mdesign-graph.umd.js";
import { showDetailTermCommon } from "@/modules/model/service/termBankService";
import { actionManager } from "@/action/ActionManager";
import { ActionKey } from "@/action/ActionKey";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  encrypted?: boolean;
  editDivHeight?: number;
  maxlength?: number;
}>();

const text = ref(props.row.value as string);
const projectId = ref(app.activeProject!.id);
let showDiv = ref<HTMLElement>();
let editDivHeight = ref(props.editDivHeight ? Math.max(props.editDivHeight, 24) + "px" : "24px");
const isCreateElement = computed(() => {
  return props.row.key === PropertyKey["Customization::PackageStructureConfiguration-createElement"];
});
watch(
  () => props.row.value,
  newVal => (text.value = newVal as string)
);
watch(
  () => props.selected,
  newVal => {
    // 从非编辑状态进入编辑状态，将显示时候的高度复制给编辑状态的div
    if (newVal && showDiv.value) {
      const height = Math.max(showDiv.value.clientHeight, 24) + "px";
      editDivHeight.value = height;
    }
  }
);

const handelChange = async () => {
  const dto = propertyUtil.getUpdatePropertyDtoByPropertyRow(props.row, app.activeProject!.id);
  dto.value = text.value;
  if (props.row.key === "87983233416574912") {
    dto.updateMethod = "updateTCPOpaqueActionTCPAddress";
  }
  let res = await modelService.updateModelProperty(dto);

  if (res) {
    app.$bus.emit(BusEvent.REFRESH_PROPERTY, props.row.modelId);
  }
};

async function handleEditPackageInfo() {
  if (isModelDisabled && isModelDisabled.value) return;
  const action = actionManager.getAction(ActionKey.ModelStructureAction);
  action?.editorRun?.(props.row, {
    modelId: props.row.modelId,
    projectId: projectId.value
  });
}
async function handleClick() {
  if (isModelDisabled && isModelDisabled.value) return;
  await htmlEditorWindow
    .popup({
      projectId: projectId.value,
      text: encodeURIComponent((props.row.value as string) || ""),
      modelId: props.row.modelId,
      modelIds: props.row.modelIds && props.row.modelIds.length ? [...props.row.modelIds] : undefined,
      propertyKey: props.row.key
    })
    .then(async res => {
      if (res.success) {
        const dto = propertyUtil.getUpdatePropertyDtoByPropertyRow(props.row, app.activeProject!.id);
        dto.value = res.value;
        if (props.row.key === "87983233416574912") {
          dto.updateMethod = "updateTCPOpaqueActionTCPAddress";
        }
        const mid = await modelService.updateModelProperty(dto);
        mid && app.$bus.emit(BusEvent.REFRESH_PROPERTY, props.row.modelId);
      }
    })
    .catch((err: any) => err && console.error(err));
}

const isAHtmlItem = computed(() => {
  if (!propertyUtil.isHtmlTextProperty(props.row.key, props.row.dataType)) {
    return false;
  }
  if (typeof text.value === "string") {
    return text.value?.startsWith("<");
  } else {
    return false;
  }
});

const needHtmlEntry = computed(() => {
  if (props.row.key === GlobalNumberType["NumberPart-initialValue"]) {
    return false;
  }
  if (props.row.readonly || isModelDisabled?.value) {
    return false;
  }
  return propertyUtil.isHtmlTextProperty(props.row.key, props.row.dataType);
});

const containTermName = computed(() => {
  let _containTermName: ContainTermName[] = [];
  _containTermName = splitOriginTextWithTerms((props.row.value as string) || "", props.row.terms || []);
  return _containTermName;
});

function showDetailTerm(event: MouseEvent, termText: string) {
  if (props.row.readonly || isModelDisabled?.value) return;
  showDetailTermCommon(event, termText);
}
</script>

<style lang="scss">
.v-html-textarea {
  display: flex;
  .v-editor-createElement {
    display: flex;
    justify-content: space-between;
    padding: 0 8px;
    width: 100%;
  }
  .v-editor-textarea {
    flex: 1 1 100px;
    .el-textarea__inner {
      height: 100%;
      font-size: 11px;
      line-height: 24px;
      resize: none;
      padding: 0 7px;
      &:hover {
        box-shadow: none;
      }
    }
  }
  > .img-btn {
    display: flex;
    align-items: center;
    flex: 0 0 auto;
    width: 29px;
    padding-left: 5px;
  }
}
</style>
